﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace MessMain
{
    public class ReadMsgSock
    {
        public String confName, confUsrs, confMsg, from;
        private TcpClient cl;
        string client = "";
        private NetworkStream myNetStream;
        private Comunication c;
        private List<string> listusers = new List<string>();
        private string limba;

        public ReadMsgSock(TcpClient cl, Comunication cc, string limba)
        {
            this.cl = cl;
            this.limba = limba;
            c = cc;
        }

        public void run()
        {
            try
            {
                myNetStream = cl.GetStream();
                while (this.cl.Connected)
                {
                    byte[] bytes = new byte[cl.ReceiveBufferSize];
                    myNetStream.Read(bytes, 0, bytes.Length);
                    string returndata = Encoding.ASCII.GetString(bytes);
                    //Console.WriteLine("[server Response]: " + returndata);
                    //c.tbi.text1.Text += returndata;
                    returndata = returndata.TrimEnd('\0');
                    if (returndata.StartsWith("/userlist"))
                    {
                        insercRecord(returndata);
                    }

                    /*if (returndata.StartsWith("/youare"))
                    {
                        c.myName = returndata.Substring(8);
                        this.client = returndata.Substring(8).Trim();
                        c.Invoke((MethodInvoker)delegate
                           {
                               c.Text = "Bun venit " + this.client.Trim();
                           });

                    }*/

                    if (returndata.StartsWith("/userdiss"))
                    {
                        char[] seps = { ' ' };
                        String[] values = returndata.Split(seps);
                        String from = values[1];
                        c.Invoke((MethodInvoker)delegate
                        {
                            if (c.users.Items.Contains((string)from))
                            {
                                c.users.Items.Remove(from);
                                TabItems us = null;
                                for (int i = 0; i < c.tablist.Count; i++)
                                {
                                    if (c.tablist[i].Text.Equals(from.Trim()))
                                    {
                                        us = c.tablist[i];
                                    }
                                }

                                if (us != null)
                                {
                                    //c.tabControl2.Controls.Remove(us);
                                    us.needRemove = true;


                                    XMLParser parser = new XMLParser(@"C:\Language" + limba + ".xml");

                                    Dictionary<string, string> dict =
                                        parser.ExtractAttributePairs("MesajeEroare", string.Empty, string.Empty, "name", "formula");

                                    MessageBox.Show(dict["MessUtil"] + from + dict["MessUtil"],
                                                    dict["TitluEroare"],
                                                    MessageBoxButtons.OK,
                                                    MessageBoxIcon.Error);
                                   
                                    us.text1.Text += " Utilizatorul " + from + " a iesit.\r\n";
                                    us.gbConectat.Text = "Nu sunteti conectat cu nimeni.";
                                    //c.tablist.Remove(us);
                                }

                                for (int i = 0; i < c.tablist.Count; i++)
                                {
                                    if (c.tablist[i].isConf)
                                    {
                                        if (c.tablist[i].listUsers.Contains((string)from))
                                        {
                                          
                                            c.tablist[i].listUsers.Remove((string)from);
                                            for (int t = 0; t < c.tablist[i].listUsers.Count; t++)
                                            {
                                                if (t == (c.tablist[i].listUsers.Count - 1))
                                                {
                                                    c.tablist[i].gbConectat.Text += c.tablist[i].listUsers[i];
                                                }
                                                else
                                                {
                                                    c.tablist[i].gbConectat.Text += c.tablist[i].listUsers[i] + ", ";
                                                }
                                            }
                                            c.tablist[i].text1.Text += " Utilizatorul " + from + " a iesit din conferinta.\r\n";
                                            if (c.tablist[i].listUsers.Count == 0)
                                            {
                                                c.tablist[i].text1.Text += " Toti utilizatorii au iesit din conferinta.\r\n";
                                                c.tablist[i].gbConectat.Text = "Nu sunteti conectat cu nimeni.";
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                    //   /conf nume /to us1 /msg us1 us2 us3 /users asd sad sad
                    if (returndata.StartsWith("/conf"))
                    {
                        //Console.WriteLine(returndata);
                        //c.Invoke((MethodInvoker)delegate
                        //{
                        //    c.users.Items.Add(returndata);
                        //});
                        bool cnp = false;
                        if (returndata.Contains("/cnp"))
                        {
                            parseConfcnp(returndata);
                            cnp = true;
                        }
                        else
                            parseConfmess(returndata);
                        TabItems us = null;
                        for (int i = 0; i < c.tablist.Count; i++)
                        {
                            if (c.tablist[i].Text.Equals(confName))
                            {
                                us = c.tablist[i];
                            }
                        }
                        if (us == null)
                        {
                            TabItems tb;
                            c.Invoke((MethodInvoker)delegate
                            {
                                tb = new TabItems(limba);
                                ConfAcc confCc = new ConfAcc(limba);
                                c.confC = confCc;
                                c.confC.tbi = tb;
                                confCc.c = c;
                                confCc.rms = this;
                                confCc.lbAcceptare.Text += "in conferinta: " + confName + "\r\nPersoane care au mai fost invitate: " + confUsrs.TrimEnd('\0') + "\r\n\r\n\r\n                                                  Acceptati?";
                                confCc.Show();
                                c.tablist.Add(tb);
                            });
                        }
                        else
                        {
                            us.Invoke((MethodInvoker)delegate
                            {
                                if (!cnp)
                                {
                                    us.text1.Text += " ";
                                    us.text1.Text += from;
                                    us.text1.Text += " : ";
                                    us.text1.Text += confMsg;
                                    us.text1.Text += "\r\n";
                                    us.text1.SelectionStart = us.text1.TextLength;
                                    us.text1.ScrollToCaret();
                                }
                                else
                                {
                                    us.loadpacient(confMsg);
                                }
                            });
                        }
                    }

                    if (returndata.StartsWith("/already"))
                    {
                        XMLParser xml = new XMLParser(@"C:\Language" + limba + ".xml");
                        Dictionary<string,string> erori = xml.ExtractAttributePairs("MesajeEroare", string.Empty, string.Empty, "name", "formula");
                        MessageBox.Show(erori["already"], erori["TitluEroare"],MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Environment.Exit(0);
                    }

                    if (returndata.StartsWith("/msg"))
                    {
                        //c.tbi.text1.Text += returndata;                                         
                        char[] seps = { ' ' };
                        String[] values = returndata.Split(seps);
                        string msg = "";
                        String from = values[1];
                        //c.tbi.text1.Text += from;
                        TabItems us = null;
                        for (int i = 0; i < c.tablist.Count; i++)
                        {
                            if (c.tablist[i].Text.Equals(from))
                            {
                                us = c.tablist[i];
                            }
                        }
                        if (us != null)
                        {
                            if (!c.tabControl2.Controls.Contains(us))
                            {
                                c.Invoke((MethodInvoker)delegate
                                {
                                    c.setCtlTab2(us);
                                });
                            }
                            for (int i = 2; i < values.Length; i++)
                            {
                                msg += values[i] + " ";
                            }
                            us.Invoke((MethodInvoker)delegate
                               {
                                   us.text1.Text += " ";
                                   us.text1.Text += from;
                                   us.text1.Text += " : ";
                                   us.text1.Text += msg;
                                   us.text1.Text += "\r\n";
                                   us.text1.SelectionStart = us.text1.TextLength;
                                   us.text1.ScrollToCaret();
                               });
                        }
                        else
                        {
                            c.Invoke((MethodInvoker)delegate
                            {
                                TabItems tbi = new TabItems(limba);
                                tbi.c = c;
                                tbi.myName = Comunication.myName;
                                tbi.addUser(from);
                                tbi.upDateVar();
                                c.tablist.Add(tbi);
                                c.setCtlTab2(tbi);
                                for (int i = 2; i < values.Length; i++)
                                {
                                    msg += values[i] + " ";
                                }
                                tbi.text1.Text += " ";
                                tbi.text1.Text += from;
                                tbi.text1.Text += " : ";
                                tbi.text1.Text += msg;
                                tbi.text1.Text += "\r\n";
                                tbi.text1.SelectionStart = tbi.text1.TextLength;
                                tbi.text1.ScrollToCaret();
                            });
                        }
                    }

                    if (returndata.StartsWith("/cnp"))
                    {
                        //c.tbi.text1.Text += returndata;                                         
                        char[] seps = { ' ' };
                        String[] values = returndata.Split(seps);
                        string msg = "";
                        String from = values[1];
                        //c.tbi.text1.Text += from;
                        TabItems us = null;
                        for (int i = 0; i < c.tablist.Count; i++)
                        {
                            if (c.tablist[i].Text.Equals(from))
                            {
                                us = c.tablist[i];
                            }
                        }
                        if (us != null)
                        {
                            if (!c.tabControl2.Controls.Contains(us))
                            {
                                c.Invoke((MethodInvoker)delegate
                                {
                                    c.setCtlTab2(us);
                                });
                            }
                            for (int i = 2; i < values.Length; i++)
                            {
                                msg += values[i] + " ";
                            }
                            us.Invoke((MethodInvoker)delegate
                            {
                                us.loadpacient(msg);
                            });
                        }
                        else
                        {
                            c.Invoke((MethodInvoker)delegate
                            {
                                TabItems tbi = new TabItems(limba);
                                tbi.c = c;
                                tbi.myName = Comunication.myName;
                                tbi.addUser(from);
                                tbi.upDateVar();
                                c.tablist.Add(tbi);
                                c.setCtlTab2(tbi);
                                for (int i = 2; i < values.Length; i++)
                                {
                                    msg += values[i] + " ";
                                }
                                tbi.loadpacient(msg);

                            });
                        }

                    }
                }
                //Console.WriteLine("ServerDeconectat1");
                myNetStream.Close();
                cl.Close();
            }
            catch (System.IO.IOException)
            {
                //Console.WriteLine("ServerDeconectat3");
                myNetStream.Close();
                cl.Close();
            }
        }
        public void insercRecord(string r)
        {
            char[] seps = { ' ' };
            String[] values = r.Split(seps);
            for (int i = 1; i < values.Length - 1; i++)
            {
                if (values[i].Trim().CompareTo("") != 0)
                {
                    if (!c.users.Items.Contains(values[i]))
                    {
                        string it = values[i].Trim();
                        if (it.CompareTo(client) == 0)
                        {
                        }
                        else
                        {
                            c.Invoke((MethodInvoker)delegate
                           {
                               c.users.Items.Add(values[i]);
                               listusers.Add(values[i]);
                           });

                        }
                    }
                }
            }
            verifyOfline(r);
        }

        private void verifyOfline(string r)
        {
            for (int i = 0; i < listusers.Count; i++)
            {
                string el = listusers.ElementAt(i);
                if (!contains(r, el))
                {
                    listusers.Remove(el);
                    c.Invoke((MethodInvoker)delegate
                    {
                        //c.users.Items.Remove(el);
                        if (c.users.Items.Contains((string)el))
                        {
                            c.users.Items.Remove(el);
                            TabItems us = null;
                            for (i = 0; i < c.tablist.Count; i++)
                            {
                                if (c.tablist[i].Text.Equals(el))
                                {
                                    us = c.tablist[i];
                                }
                            }
                            if (us != null)
                            {
                                //c.tabControl2.Controls.Remove(us);
                                us.needRemove = true;
                                MessageBox.Show("Utilizatorul: " + el + " a iesit.");
                                us.text1.Text += " Utilizatorul " + el + " a iesit.\r\n";
                                us.gbConectat.Text = "Nu sunteti conectat cu nimeni.";
                                //c.tablist.Remove(us);
                            }
                            for (int ii = 0; ii < c.tablist.Count; ii++)
                            {
                                if (c.tablist[ii].isConf)
                                {
                                    if (c.tablist[ii].listUsers.Contains((string)el))
                                    {
                                       
                                        c.tablist[ii].listUsers.Remove((string)el);
                                        for (int t = 0; t < c.tablist[ii].listUsers.Count; t++)
                                        {
                                            if (t == (c.tablist[ii].listUsers.Count - 1))
                                            {
                                                c.tablist[ii].gbConectat.Text += c.tablist[ii].listUsers[ii];
                                            }
                                            else
                                            {
                                                c.tablist[ii].gbConectat.Text += c.tablist[ii].listUsers[ii] + ", ";
                                            }
                                        }
                                        c.tablist[ii].text1.Text += " Utilizatorul " + el + " a iesit din conferinta.\r\n";
                                        if (c.tablist[ii].listUsers.Count == 0)
                                        {
                                            c.tablist[ii].text1.Text += " Toti utilizatorii au iesit din conferinta.\r\n";
                                            c.tablist[ii].gbConectat.Text = "Nu sunteti conectat cu nimeni.";
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }

        }
        private bool contains(string r, string el)
        {
            char[] seps = { ' ' };
            String[] values = r.Split(seps);
            for (int i = 1; i < values.Length - 1; i++)
            {
                if (values[i].CompareTo(el) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        public int indexOf(string dc, string w)
        {
            char[] c1 = dc.ToCharArray();
            char[] c2 = w.ToCharArray();
            int nr = 0;
            for (int i = 0; i < c1.Length; i++)
            {
                nr = 0;
                if (c1[i] == c2[0])
                {
                    nr++;
                    for (int j = 1; j < c2.Length; j++)
                    {
                        if (c1[i + j] == c2[j])
                        {
                            nr++;
                        }
                    }
                    if (nr == c2.Length)
                        return i;
                }
            }
            return -1;
        }
        //   /conf nume /to us1 /msg us1 us2 us3 /users asd sad sad /from uu
        public void parseConfmess(string s)
        {
            int indexI, indexF;
            indexI = indexOf(s, "/conf");
            indexF = indexOf(s, "/to");
            confName = s.Substring(indexI + 5, indexF - 5).Trim();
            indexI = indexOf(s, "/msg");
            indexF = indexOf(s, "/users");
            confMsg = s.Substring(indexI + 4, indexF - indexI - 4).Trim();
            indexI = indexOf(s, "/users");
            indexF = indexOf(s, "/from");
            confUsrs = s.Substring(indexI + 6, indexF - indexI - 6).Trim();
            indexI = indexOf(s, "/from");
            from = s.Substring(indexI + 5).Trim();
        }

        public void parseConfcnp(string s)
        {
            int indexI, indexF;
            indexI = indexOf(s, "/conf");
            indexF = indexOf(s, "/to");
            confName = s.Substring(indexI + 5, indexF - 5).Trim();
            indexI = indexOf(s, "/cnp");
            indexF = indexOf(s, "/users");
            confMsg = s.Substring(indexI + 4, indexF - indexI - 4).Trim();
            indexI = indexOf(s, "/users");
            indexF = indexOf(s, "/from");
            confUsrs = s.Substring(indexI + 6, indexF - indexI - 6).Trim();
            indexI = indexOf(s, "/from");
            from = s.Substring(indexI + 5).Trim();
        }
    }
}
